/**
 * 
 */
package com.nari.heatshare.dao.springjdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.nari.coreframe.dao.springjdbc.AbstractDaoImpl;
import com.nari.coreframe.dao.springjdbc.extendcore.ResultSetMapHandler;
import com.nari.heatshare.utils.queryvo.HeatMeterDataCustomizedQuery;
import com.nari.heatshare.utils.queryvo.HeatMeterDataRecordExtendQuery;
import com.nari.platform.date.CalendarUtils;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.platform.sqlfunc.mysql.DateFunctionUtils4MySQL;
import com.nari.platform.utils.StringUtils;
import com.nari.rescontroller.dao.IResourceAccessControlDao;

/**
 * 
 * @author Xiaopeng
 * @date 2014-12-10
 */
public class HeatMeterDataJdbcDaoImpl extends AbstractDaoImpl 
		implements IHeatMeterDataJdbcDao {
	private Logger logger = Logger.getLogger(HeatMeterDataJdbcDaoImpl.class);
	private IResourceAccessControlDao iResourceAccessControlDao;
	
	/**
	 * 分页查询热量表数据定制查询列表
	 * @param projectUID
	 * @param communityUID
	 * @param recordTimeStart
	 * @param recordTimeEnd
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-12-17
	 */
	public ResultWithPageCond<HeatMeterDataCustomizedQuery> queryCustomizedQueryPage(String projectUID, 
			String communityUID, Date recordTimeStart, Date recordTimeEnd,
			PageCond pageCond) throws Exception {
		Date startTime = CalendarUtils.getMinCalBasedSrcCal(CalendarUtils.getInstance(recordTimeStart));
		Date endTime = CalendarUtils.getMaxCalBasedSrcCal(CalendarUtils.getInstance(recordTimeEnd));
		String querySQL = "select hm.t_community_id as communityUID," +
								 DateFunctionUtils4MySQL.dateSqlField2StringFunc("inner_grep.t_record_time")+" as recordDate," +
								 "count(inner_grep.t_meter_no) as heatMeterDataCounter," +
								 "hm.t_project_id as projectUID " +
						  "from (select inner_hmd.t_meter_no as t_meter_no," +
						  			   "inner_hmd.t_record_time as t_record_time " +
						  		"from p_heat_meta_data inner_hmd " +
						  		"where inner_hmd.t_record_time between '"+CalendarUtils.parseDateTimeToString(startTime)+"' " +
						  									  "and '"+CalendarUtils.parseDateTimeToString(endTime)+"') inner_grep,base_heat_meter_info hm " +
						  "where 1=1";
		//权限资源匹配
		String authorityRes = iResourceAccessControlDao.queryAuthorityProjResSql();
		if(!"".equals(authorityRes)) { //非管理员用户授权项目权限
			List<Object> projectUIDList = this.jdbcTemplate.queryForList(authorityRes, Object.class);
			String formatProjectUIDList = StringUtils.formatIDsByList(projectUIDList);
			formatProjectUIDList = StringUtils.formatIDListWithSyntax(formatProjectUIDList, ",", "'");
			querySQL += " and hm.t_project_id in("+formatProjectUIDList+")";
		}
		//设置查询字段
		if(projectUID!=null && !"".equals(projectUID)) {
			querySQL += " and hm.t_project_id='"+projectUID+"'";
		}
		if(communityUID!=null && !"".equals(communityUID)) {
			querySQL += " and hm.t_community_id='"+communityUID+"'";
		}
		//设置表关联
		querySQL += " and inner_grep.t_meter_no=hm.t_meter_no";
		//定制查询分组
		querySQL += " group by hm.t_community_id,"+DateFunctionUtils4MySQL.dateSqlField2StringFunc("inner_grep.t_record_time")+",hm.t_project_id " +
				"having count(inner_grep.t_meter_no)>0";
		//结果集个数查询
		String couterSQL = "select count(*) from ("+querySQL+") inner_counter";
		System.out.println("couterSQL:"+couterSQL);
		int total = this.jdbcTemplate.queryForInt(couterSQL);
		//定制查询排序及分页
		querySQL += " order by recordDate desc,hm.t_community_id asc " +
				"limit "+pageCond.getStart()+","+pageCond.getLimit();
		logger.debug("querySQL:"+querySQL);
//		System.out.println("querySQL:"+querySQL);
		//封装查询结果
		final List<HeatMeterDataCustomizedQuery> customizedQueryList = new ArrayList<HeatMeterDataCustomizedQuery>();
		this.getJdbcTemplate().query(querySQL, new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				HeatMeterDataCustomizedQuery customizedQuery = new HeatMeterDataCustomizedQuery();
				customizedQuery.setProjectUID(rs.getString("projectUID"));
				customizedQuery.setCommunityUID(rs.getString("communityUID"));
				customizedQuery.setRecordDate(rs.getString("recordDate"));
				customizedQuery.setHeatMeterDataCounter(rs.getInt("heatMeterDataCounter"));
				//小区所属热量表个数
				String hmCounterSQL = "select count(*) from base_heat_meter_info hm " +
						"where hm.t_community_id='"+customizedQuery.getCommunityUID()+"'";
				int heatMeterNum = getJdbcTemplate().queryForInt(hmCounterSQL);
				customizedQuery.setHeatMeterNum(heatMeterNum);
				customizedQueryList.add(customizedQuery);
			}
		});
		//构造返回类型
		pageCond.setTotal(total);
		ResultWithPageCond<HeatMeterDataCustomizedQuery> customizedQueryPage = new ResultWithPageCond<HeatMeterDataCustomizedQuery>();
		customizedQueryPage.setList(customizedQueryList);
		customizedQueryPage.setPageCond(pageCond);
		return customizedQueryPage;
	}
	
	/**
	 * 根据热量表数据UID查询其对应的档案资料扩展信息
	 * @param meterDataUIDList 热量表数据UID列表
	 * 格式：XXX,XXX,XXX
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2015-1-23
	 */
	public Map<String, HeatMeterDataRecordExtendQuery> queryHmdRecordExtend(String meterDataUIDList) throws Exception {
		//热量表表号列表格式化
		String meterDataUIDListFormat = StringUtils.formatIDListWithSyntax(meterDataUIDList, ",", "'");
		String querySQL = "select hmd.ID as meterDataUID," +
								 "hmd.t_meter_no as meterNo," +
								 "b.t_building_no as buildingCode," +
								 "b.t_building_area as buildingArea " +
						  "from p_heat_meta_data hmd," +
						  	   "base_heat_meter_info hm," +
						  	   "base_building_info b " +
						  "where hmd.id in("+meterDataUIDListFormat+") " +
						  "and hmd.t_meter_no=hm.t_meter_no " +
						  "and hm.t_building_id=b.ID";
		logger.debug("querySQL:"+querySQL);
//		System.out.println("querySQL:" + querySQL);
		//封装查询结果
		final Map<String, HeatMeterDataRecordExtendQuery> extendQueryMap = new HashMap<String, HeatMeterDataRecordExtendQuery>();
		this.jdbcTemplate.query(querySQL, new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				try {
					ResultSetMapHandler<HeatMeterDataRecordExtendQuery> mapper = new ResultSetMapHandler<HeatMeterDataRecordExtendQuery>();
					//注意：这里已完成了ResultSet的迭代(取代了Spring JDBC的迭代处理)
					List<HeatMeterDataRecordExtendQuery> hmdExtendList = mapper.mapResultSet2Object(rs, HeatMeterDataRecordExtendQuery.class);
					if(hmdExtendList!=null && hmdExtendList.size()>0) {
						for(HeatMeterDataRecordExtendQuery hmdExtend: hmdExtendList) {
							extendQueryMap.put(hmdExtend.getMeterDataUID(), hmdExtend);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error(e.getMessage());
					throw new SQLException(e.getMessage());
				}
			}
		});
		return extendQueryMap;
	}

	/**
	 * @return the iResourceAccessControlDao
	 */
	public IResourceAccessControlDao getiResourceAccessControlDao() {
		return iResourceAccessControlDao;
	}

	/**
	 * @param iResourceAccessControlDao the iResourceAccessControlDao to set
	 */
	public void setiResourceAccessControlDao(
			IResourceAccessControlDao iResourceAccessControlDao) {
		this.iResourceAccessControlDao = iResourceAccessControlDao;
	}
	
}
